<template>
  <div style="height: 100%" class="chat-detail-scroll-container">
    <div v-if="messageList.length>0" class="chat-detail-content">
      <div class="chat-detail-main">
        <div class="chat-header">
          <div class="chat-header-content" @click="() => editConversation()">
            <span class="conversationTitle">对话试用 </span>
          </div>
        </div>
        <div class="chat-content-container">
          <div class="sessionItem">
            <div v-for="(item, index) in messageList" :key="index">
              <div class="userItem sessionItem-item" v-if="item.role == 'user'">
                <div class="userItem-question content">
                  <p class="userP">{{ item.content }}</p>
                </div>
              </div>
              <div class="sessionItem-item" v-else>
                <div class="systemItem sessionItem-item">
                  <div class="systemItem-avatar avatar">
                    <svg-icon
                      style="width: 30px; height: 30px"
                      icon-class="jiqirenmiddle"
                    />
                  </div>
                  <div class="systemItem-answer content">
                    <div class="reasoningContent" v-if="item.reasoningContent">
                      <div class="reasoningBtn">
                        <div
                          class="ds-icon reasoningIcon"
                          style="font-size: 12px; width: 12px; height: 12px"
                        >
                          <i class="el-icon-s-opportunity"></i>
                        </div>
                        慢思考
                        <div
                          class="ds-icon reasoningArrow"
                          style="
                            font-size: 10px;
                            width: 10px;
                            height: 10px;
                            margin-left: 10px;
                          "
                          @click="retractReasoning"
                        >
                          <i
                            :class="`${
                              isRetract
                                ? 'el-icon-arrow-up'
                                : 'el-icon-arrow-down'
                            }`"
                          ></i>
                        </div>
                      </div>
                      <div v-show="!isRetract" class="reasoningMarkdown">
                        <markdown-it-vue
                          class="markdown-item"
                          :content="item.reasoningContent"
                        />
                      </div>
                    </div>
                    <markdown-it-vue
                      class="markdown-item"
                      :content="item.content"
                    />
                    <span
                      class="span-icon-loading flex-item"
                      v-show="index == messageList.length - 1"
                      v-loading="item.anserLoading"
                    ></span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="chat-action">
          <ChatInput
            :anserLoading="
              messageList.length > 0
                ? messageList[messageList.length - 1].anserLoading
                : false
            "
            @send-message="sendMessage"
            @interrupt-request="interruptRequest"
            @clear-messages="clearMessages"
          />
        </div>
      </div>
    </div>
    <div v-else class="placeholder-container chat-detail-main">
      <div class="additional-element chat-content-container firstCommendationList"
      >
        <div class="chat-container">
          <p style="font-size: 22px; line-height: 60px">
            <svg-icon
              style="width: 60px; height: 60px; margin-right: 4px"
              icon-class="jiqirenlarge"
            />
            您好，我是AI问答助手，请问有什么可以帮到您？
          </p>
        </div>
        <div class="des">
          {{welcomeConfig&&welcomeConfig.welcomeText}}
        </div>
        <div class="firstCommendationListM">
          <RecommendationList
            @send-message="sendMessage"
            :pecommendationList="welcomeConfig&&welcomeConfig.questions.filter(item => {
              return item!==''
            })"
          ></RecommendationList>
        </div>
      </div>
      <div class="chat-action">
        <ChatInput
          :anserLoading="
            messageList.length > 0
              ? messageList[messageList.length - 1].anserLoading
              : false
          "
          @send-message="sendMessage"
          @interrupt-request="interruptRequest"
          @clear-messages="clearMessages"
        />
      </div>
    </div>
  </div>
</template>
  
  <script>
import MarkdownItVue from "markdown-it-vue";
import "markdown-it-vue/dist/markdown-it-vue.css";
import ChatInput from "@/components/ai/components/ChatInput.vue";
import RecommendationList from "@/components/ai/components/RecommendationList.vue";
import { setAnswerStatus } from "@/api/counterAssistant/session";
import { getToken } from "@/utils/auth";
import { fetchEventSource } from "@microsoft/fetch-event-source";

import { handleData, processQueue } from "@/utils/index";
let functionQueue = [];
export default {
  name: "dialogueTrial",
  components: { MarkdownItVue, ChatInput, RecommendationList },
  props: {
    welcomeConfig: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      selectedConversation: null,
      // displayMessages: [],
      answerStatus: 0,
      isRetract: false,
      messageList: [],
      // agentId: 0,
      // chatId: 0,
      id: 0,
      anserLoading: false,
      ctrlAbout: null,
    };
  },
  mounted() {
    this.id = this.$route.params && this.$route.params.id;
  },
  methods: {
    retractReasoning() {
      this.isRetract = !this.isRetract;
    },
    // 获取问答列表的滚动条(问答页面在最底部时才滚动)
    scrollAtBottom() {
      this.$nextTick(() => {
        const container = document.querySelector(
          ".chat-detail-scroll-container"
        );
        if (container) {
          if (
            container.scrollTop + container.clientHeight + 100 >
            container.scrollHeight
          ) {
            container.scrollTop = container.scrollHeight;
          }
        }
      });
    },

    interruptRequest() {
      this.anserLoading = false;
      functionQueue = [];
      this.ctrlAbout.abort();
    },
    // 问答提交逻辑
    async sendMessage(messageContent, answerStatus) {
      const answerObj = {
        role: "assistant",
        content: "",
        reasoningContent: "",
        question: messageContent,
      };
      this.messageList.push({
        role: "user",
        content: messageContent,
      });
      this.messageList.push(answerObj);
      this.ctrlAbout = new AbortController();
      this.anserLoading = true;

      // 发送 SSE 请求
      const that = this;
      const proxyUrl = process.env.VUE_APP_BASE_API + "/qa/questionStream";

      try {
        fetchEventSource(proxyUrl, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Accept: "text/event-stream",
            Authorization: "Bearer " + getToken(),
          },
          signal: that.ctrlAbout.signal,
          body: JSON.stringify({
            // agentId: this.agentId,
            // chatId: this.chatId,
            id: this.id,
            streaming: true,
            queryText: messageContent,
            answerStatus: answerStatus,
            language: "zh",
          }),
          onmessage(ev) {
            // 清空内容
            let trimData = "";
            let reasoningContent = "";
            try {
              const parsedData = JSON.parse(ev.data);
              if (parsedData.sourceDocs) {
                that.ctrlAbout.abort();
                const wrappedCallback = () =>
                  handleData("end", () => {
                    that.anserLoading = false;
                  });
                functionQueue.push(wrappedCallback);
                processQueue(); // 尝试立即处理队列（如果当前没有在处理）
                return;
              }
              if (parsedData.think) {
                reasoningContent = parsedData.msg;
                // 直接显示在页面的代码
                const wrappedCallback = () =>
                  handleData(reasoningContent, (data) => {
                    const messageData = answerObj.reasoningContent;
                    answerObj.reasoningContent = messageData + data;
                    that.$nextTick(() => {
                      that.scrollAtBottom();
                    });
                  });
                functionQueue.push(wrappedCallback);
                processQueue(); // 尝试立即处理队列（如果当前没有在处理）
              } else {
                trimData = parsedData.msg;
                // 直接显示在页面的代码
                const wrappedCallback1 = () =>
                  handleData(trimData, (data) => {
                    const messageData = answerObj.content;
                    answerObj.content = messageData + data;
                    that.$nextTick(() => {
                      that.scrollAtBottom();
                    });
                  });
                functionQueue.push(wrappedCallback1);
                processQueue(); // 尝试立即处理队列（如果当前没有在处理）
              }
            } catch (e) {
              console.log("catch", e);
              that.anserLoading = false;
              that.ctrlAbout.abort();
            }
          },
          onclose() {
            that.anserLoading = false;
            that.ctrlAbout.abort();
          },
          onerror(err) {},
        });
      } catch (error) {
        // console.log('catch111',error);
        that.anserLoading = false;
        that.ctrlAbout.abort();
      }
      // 创建一个函数队列
      functionQueue = [];
      let isProcessingQueue = false;
      const processQueue = () => {
        if (functionQueue.length === 0 || isProcessingQueue) return;
        isProcessingQueue = true;
        const currentFunction = functionQueue.shift();
        currentFunction()
          .then(() => {
            isProcessingQueue = false;
            processQueue(); // 递归调用以处理下一个函数
          })
          .catch((error) => {
            isProcessingQueue = false;
            processQueue(); // 即使出错也继续处理下一个函数
          });
      };
    },
    clearMessages() {
      this.answerStatus = 1;
      const data = {
        id: 1,  //
        answerStatus: this.answerStatus,
      };
      setAnswerStatus(data).then((response) => {
        if (response.code == 200) {
          this.$modal.msgSuccess("清理成功");
        }
      });
    },
  },
};
</script>
  
<style scoped lang="scss">
.chat-detail-scroll-container {
  flex: 1;
  overflow: auto;
  background: #fff;
  position: relative;

  .placeholder-container {
    justify-content: center;
    align-items: center;
    height: 100%;
    font-size: 16px;
    color: #9e9e9e;
    line-height: 22px;
    text-align: left;
    flex-direction: column;
    flex-grow: 1;
    // height: 100%;
    display: flex;
    position: relative;
    .additional-element {
      display: flex;
      margin-bottom: 10px; /* 添加间距 */
      width: 100%;
      text-align: center;
      justify-content: center;
      align-items: center;
      flex-direction: column; /* 如果需要垂直排列子元素 */
      width: 100%;
      max-width: 100%;
      box-sizing: border-box;
      // flex-grow: 1;
      // margin: auto;
      padding: 38px 0 40px;
      p {
        display: flex;
        margin-bottom: 20px;
        font-size: 16px;
        color: #9e9e9e;
        // padding-left: 12px;
      }
      .chat-container {
        text-align: left;
        i {
          color: #409eff;
        }
      }
    }
  }
  .chat-detail-content {
    display: flex;
    flex: 1;
    min-width: 0;
    .chat-detail-main {
      flex: 1;
      min-width: 0;
      height: 100%;
      display: flex;
      flex-direction: column;
      position: relative;
      align-items: center;
      min-height: calc(100vh - 86px);
      .chat-header {
        background: #fff;
        box-sizing: border-box;
        width: 100%;
        padding: 7px 50px;
        height: 46px;
        position: -webkit-sticky;
        position: sticky;
        top: 0;
        left: 0;
        min-width: 375px;
        max-width: 1090px;
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 6px;
        z-index: 10;

        .chat-header-content {
          max-width: 500px;
          display: flex;
          justify-content: center;
          // justify-content: flex-start;
          align-items: center;
          padding: 4px 8px;
          border-radius: 8px;
          position: relative;
          box-sizing: border-box;
          cursor: pointer;

          .conversationTitle {
            border-radius: 8px;
            color: #262626;
            // background: #f0f0f0;
            display: inline-block;
            padding: 8px;
            width: 100%;
            font-size: 18px;
            font-weight: 700;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            &:hover {
              border: 1px solid #d9d9d9;
            }
          }
        }
      }
    }
    .chat-content-container {
      box-sizing: border-box;
      width: 100%;
      max-width: 1090px;
      display: flex;
      padding: 0 16px 30px;
      flex: 1;
      .sessionItem {
        padding: 10px 20px;
        min-height: 100%;
        border-radius: 8px;
        width: 100%;
        .sessionItem-item {
          &.userItem {
            display: flex;
            // justify-content: flex-end;
            align-items: start;
            flex-direction: column;
            align-items: flex-end;
            margin-top: 20px;
            .userItem-avatar {
              padding-top: 22px;
              text-align: right;
              margin-left: 10px;
            }
            p {
              padding: 10px;
              background: #eff6ff;
              border-radius: 10px;
              // margin-right: 10px;
            }
          }
          &.systemItem {
            display: flex;
            align-items: start;
            justify-content: flex-start;
            .systemItem-avatar {
              margin-right: 10px;
              margin-top: 6px;
              i {
                color: #409eff;
              }
            }
            .systemItem-answer {
              width: 100%;
              background: #f5f5f5;
              border-radius: 10px;
              padding: 14px;
              display: flex;
              flex-wrap: wrap; /* 允许子元素换行 */
              justify-content: flex-start; /* 左对齐 */
              gap: 10px; /* 子元素之间的间距 */
              .markdown-item {
                width: 100%;
              }
              .comment {
                display: flex;
                justify-content: space-between;
                align-items: center;
                width: 100%;
                .show-left {
                  .comment-refresh {
                    margin-right: 10px;
                  }
                  i {
                    margin-right: 6px;
                    cursor: pointer;
                    font-size: 24px;
                  }
                }
                .show-right {
                  .el-button--medium.is-circle {
                    padding: 6px;
                  }
                }
                span {
                  margin-right: 10px;
                }
              }
              .reasoningContent {
                margin-bottom: 13px;
              }
              .reasoningBtn {
                color: #24292e;
                margin-bottom: 12px;
                font-size: 12px;
                line-height: 18px;
                cursor: pointer;
              }
              .reasoningBtn {
                background: #ccc;
                -webkit-user-select: none;
                -moz-user-select: none;
                -ms-user-select: none;
                user-select: none;
                border-radius: 10px;
                justify-content: center;
                align-items: center;
                width: fit-content;
                padding: 7px 14px;
                display: flex;
              }
              .reasoningIcon {
                margin-right: 6px;
              }
              .ds-icon {
                line-height: 0;
                display: inline-flex;
              }
              .reasoningContent .reasoningMarkdown {
                white-space: pre-wrap;
                margin: 0;
                padding: 0 0 0 13px;
                line-height: 26px;
                position: relative;
                border-left: #a6a6a6 2px solid;
                .markdown-body {
                  color: #a6a6a6 !important;
                }
              }
            }
          }
          .avatar {
            width: 40px;
            height: 40px;
            .iconfont {
              font-size: 28px;
            }
          }
        }
      }
    }
    .chat-action {
      background: #fff;
      width: 100%;
      max-width: 1090px;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      position: -webkit-sticky;
      position: sticky;
      bottom: 0;
      padding: 0 16px;
      box-sizing: border-box;
      // flex-direction: column;
      // align-items: center;
      margin-top: auto;
      // display: flex;
      // position: -webkit-sticky;
      // position: sticky;
      // bottom: 0;
    }
    .console-button {
      position: fixed;
      margin: auto;
      z-index: 15;
      top: 80px;
      right: 16px;
      padding: 6px;
      cursor: pointer;
      display: flex;
      width: 24px;
      height: 24px;
      border-radius: 12px;
      -webkit-user-select: none;
      -moz-user-select: none;
      user-select: none;
    }
    .side-console-container {
      width: 400px;
      height: calc(100vh - 200px);
      margin-right: 8px;
      box-sizing: border-box;
      position: -webkit-sticky;
      position: sticky;
      top: 56px;
      z-index: 10;
      border-radius: 20px 20px 20px 20px;
      border: 1px solid #dcdcdc;
      padding: 10px;
    }
  }
}
.chat-action {
  width: 100%;
}
.footer-input-paperclipDiv {
  display: flex;
  flex-wrap: wrap; /* 允许子元素换行 */
  gap: 10px;
  justify-content: flex-end;
  .paperclipDiv {
    background: #f3f4f6;
    border-radius: 12px;
    // width: calc(33.3333% - 8.33333px);
    transition: background-color 0.3s;
    position: relative;
    align-items: center;
    padding: 8px;
    display: flex;
    .paperclipTextDiv {
      overflow: hidden;
      .paperclipTextDiv-title {
        color: #fff;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #262626;
        min-height: 20px;
        margin: 0;
        font-size: 14px;
        font-weight: 500;
        line-height: 20px;
        overflow: hidden;
      }
    }
  }
}

.disable-click {
  pointer-events: none;
  opacity: 0.5; /* 可添加透明度样式来提示用户该元素不可用 */
}

/* 修改当前组件内 Markdown 渲染内容的行间距 */
::v-deep .reasoningMarkdown .markdown-body p {
  line-height: 1.5;
  font-size: 14px;
  margin-bottom: 0;
}

::v-deep .reasoningMarkdown .markdown-body ul,
::v-deep .reasoningMarkdown .markdown-body ol {
  line-height: 1.5;
}
</style>
  <style lang="scss">
.aq-input {
  .el-input__inner {
    padding: 10px 20px;
    height: 50px;
    border-radius: 25px;
    padding-right: 50px;
  }
  .el-input__suffix {
    right: 20px;
    top: 12px;
    height: 30px;
  }
  .aq-send-btn {
    i.icon-video-pause {
      display: inline-block;
      width: 10px;
      height: 10px;
      background: #fff;
      margin: 0 3px;
      border-radius: 3px;
    }
  }
}
.conversationInput {
  .el-input__inner {
    border-radius: 8px;
    padding-left: 8px;
  }
}
.span-icon-loading.el-loading-parent--relative {
  margin-top: 20px;
  .el-loading-spinner .circular {
    width: 24px;
    height: 24px;
  }
}
.comment-btn-popover {
  &.el-popover {
    min-width: 40px;
    padding: 8px;
  }
}
.reasoningContent .reasoningMarkdown {
  .markdown-body {
    color: #a6a6a6 !important;
  }
}
.an-qu
  .chat-detail-scroll-container
  .placeholder-container
  .firstCommendationList {
  align-items: normal;
  &.additional-element.chat-content-container {
    height: auto !important;
    flex-grow: initial;
    // margin: 0px;
    // width: 80%;
    padding: 0;
    width: 600px;
    margin: 0 auto;
    p {
      justify-content: center;
    }
  }
  .des {
    // padding: 0 144px;
    margin-bottom: 30px;
    font-size: 18px;
    color: #797979;
    line-height: 30px;
    text-align: left;
  }
  .firstCommendationListM {
    // padding: 0 144px;
    .askMe {
      font-size: 17px;
      color: #0e0e0e;
      line-height: 30px;
      text-align: left;
      margin-bottom: 20px;
    }
    .recommendation {
      // display: flex;
      // flex-wrap: wrap; /* 允许子元素换行 */
      // gap: 8px;
      // flex-direction: row;
      .recommend-prompt-item {
        // align-items: center;
        // padding: 8px;
        // display: flex;
        // margin-right: 0;
      }
    }
  }
}
.first-chat-action {
  &.chat-action {
    width: 864px;
    margin: 0 auto;
  }
  .content-footer {
    position: inherit;
    // padding: 0 130px;
  }
}
</style>